package com.you.rpc.client;

//import com.you.raft.common.rpc.entity.InvokeContext;

import com.you.rpc.entity.ResponseStatus;
import com.you.rpc.entity.ResponseCommand;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class DefaultInvokeFuture implements InvokeFuture {
    private static final ResponseCommand defaultTimeOutResponse;

    static {
        defaultTimeOutResponse = new ResponseCommand();
        defaultTimeOutResponse.setResponseBody(null);
        defaultTimeOutResponse.setStatus(ResponseStatus.TIMEOUT);
    }

    private final CountDownLatch countDownLatch = new CountDownLatch(1);
    private volatile ResponseCommand responseCommand;

    public DefaultInvokeFuture() {
        responseCommand = defaultTimeOutResponse;
    }

    /**
     * 在await时间之前到达，返回成功的响应数据
     * 达到await指定的时间后，返回默认的defaultTimeOutResponse
     *
     * @param timeout
     * @param timeUnit
     * @return
     * @throws InterruptedException
     */
    @Override
    public ResponseCommand waitResponse(long timeout, TimeUnit timeUnit) throws InterruptedException {
        this.countDownLatch.await(timeout, timeUnit);
        return responseCommand;
    }

    @Override
    public ResponseCommand waitResponse() throws InterruptedException {
        this.countDownLatch.await();
        return responseCommand;
    }

    @Override
    public void putResponse(ResponseCommand responseCommand) {
        this.responseCommand = responseCommand;
        this.countDownLatch.countDown();
    }
}
